package com.qny.ai.controller;

import com.qny.ai.common.ApiResponse;
import com.qny.ai.dto.audio.SttResponse;
import com.qny.ai.dto.audio.TtsRequest;
import com.qny.ai.service.impl.QiniuVoiceService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;

@RestController
@RequestMapping("/api/audio")
@RequiredArgsConstructor
public class AudioController {

    private final QiniuVoiceService qiniuVoiceService;

    // TTS：调用七牛云并返回 mp3 音频
    @PostMapping(value = "/tts")
    public ResponseEntity<byte[]> tts(@Valid @RequestBody TtsRequest request) {
        String text = request.getText();
        if (text == null) text = "";
        String base64 = qiniuVoiceService.ttsToBase64(text, "qiniu_zh_female_wwxkjx", "mp3");
        byte[] bytes;
        try {
            bytes = base64 != null && !base64.isEmpty() ? Base64.getDecoder().decode(base64) : new byte[0];
        } catch (Exception e) {
            bytes = new byte[0];
        }
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=tts.mp3")
                .contentType(MediaType.valueOf("audio/mpeg"))
                .body(bytes);
    }

    // 占位：STT，返回固定文本
    @PostMapping(value = "/stt", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ApiResponse<SttResponse> stt(@RequestPart("file") MultipartFile file,
                                        @RequestPart(value = "language", required = false) String language) {
        SttResponse resp = SttResponse.builder().text("占位：识别到的文本").language(language != null ? language : "zh").build();
        return ApiResponse.ok(resp);
    }
}


